<template>
  <div>
    <Card style="width: 200px; background-color: #f8f8f9">
      <p slot="title" style="text-align: center">
        新数据{{ upload_file || "导入" }}分析
      </p>
      <div style="text-align: center;">
        <input
          type="file"
          accept=".xls,.xlsx"
          class="upload_file"
          @change="readExcel($event)"
          style="opacity: 0;"
        />
        <Icon type="ios-cloud-upload" size="36" style="margin-top:-30px;line-height: 34px; display: block;"/>
      </div>
    </Card>
  </div>
</template>

<script>
import XLSX from "xlsx";

export default {
  data() {
    return {
      upload_file: "",
      lists: [],
    };
  },
  methods: {
    submit_form(datas) {
      // 给后端发送请求，更新数据
      this.axios
        .post("/api/constrol", datas)
        .then((r) => {
          this.$Message.info(r.data);
        })
        .catch((e) => {
          this.$Message.error("e" + e);
        });
    },
    readExcel(e) {
      // 读取表格文件
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确，请上传xls或者xlsx格式",
          type: "warning",
        });
        return false;
      } else {
        // 更新获取文件名
        this.upload_file = files[0].name;
      }

      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          // 从解析出来的数据中提取相应的数据

          ws.forEach((item) => {
            this.lists.push(item);
          });
          // 给后端发请求
          this.submit_form(this.lists);
          console.log(this.lists);
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
  },
};
</script>
